<?php

namespace ASW\Utility;

/**
 * 工具类
 */
class Tools
{
    /**
     * 创建 guid
     *
     * @param bool $split 是否用-间隔
     *
     * @return string
     */
    public static function createGuid(bool $split = true): string
    {
        $format = '%04X%04X-%04X-%04X-%04X-%04X%04X%04X';
        if (!$split) $format = str_replace('-', '', $format);
        return sprintf($format, mt_rand(0, 0xFFFF), mt_rand(0, 0xFFFF), mt_rand(0, 0xFFFF), mt_rand(0x4000, 0x4FFF), mt_rand(0x8000, 0xBFFF), mt_rand(0, 0xFFFF), mt_rand(0, 0xFFFF), mt_rand(0, 0xFFFF));
    }

    /**
     * 显示二进制数据
     *
     * @param string $buffer
     * @param bool $asNumber
     *
     * @return string
     */
    public static function prettyHex(string $buffer, bool $asNumber = false): string
    {
        $hex    = strtoupper(bin2hex($buffer));
        $hexArr = str_split($hex, 2);
        if ($asNumber) $hexArr = array_map(fn($b) => hexdec($b), $hexArr);
        return implode(' ', $hexArr);
    }

    /**
     * TAR压缩
     *
     * @param string $path
     * @param string $targetPath
     *
     * @return bool
     */
    public static function tar(string $path, string $targetPath): bool
    {
        if (!file_exists($path)) return false;
        $dir = dirname($path);
        exec("tar cvf $targetPath -C $dir $path");
        return true;
    }

    /**
     * 字节尺寸转换文本
     *
     * @param int $value
     *
     * @return string
     */
    public static function sizeText(int $value): string
    {
        $units = [
            'B'  => 1,
            'KB' => 1024,
            'MB' => 1024,
            'GB' => 1024,
            'TB' => 1024,
            'PB' => 1024,
            'EB' => 1024,
            'ZB' => 1024,
            'YB' => 1024,
        ];
        return self::valueText($value, $units);
    }

    /**
     * 数值转换带单位的文本
     *
     * @param int $value
     * @param array $unitList
     *
     * @return string
     */
    public static function valueText(int $value, array $unitList): string
    {
        $showValue = $value;
        if (!is_numeric($showValue)) $showValue = 0;

        $unitNames  = array_keys($unitList);
        $unitValues = array_values($unitList);
        $unitName   = $unitNames[0];

        for ($i = 0; $i < count($unitList) && $showValue >= $unitValues[$i]; $i++) {
            $showValue = $showValue / $unitValues[$i];
            $unitName  = $unitNames[$i];
        }
        $showValue = number_format($showValue, 2, '.', '');
        return "$showValue $unitName";
    }

    /**
     * 秒数转换文本
     *
     * @param int $seconds
     *
     * @return string
     */
    public static function secondsText(int $seconds): string
    {
        $units = [
            '秒'   => 1,
            '分'   => 60,
            '小时' => 60,
            '天'   => 24,
        ];
        return self::valueText($seconds, $units);
    }
}